{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "# (BONUS) Dimensionality Reduction: Nonlinear dimensionality reduction\n",
    "\n",
    "__Content creators:__ Alex Cayco Gajic, John Murray\n",
    "\n",
    "__Content reviewers:__ Kai Chen\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "---\n",
    "# Tutorial Objectives\n",
    "\n",
    "In this notebook we'll explore how dimensionality reduction can be useful for visualizing and inferring structure in your data. To do this, we will compare PCA with t-SNE, a nonlinear dimensionality reduction method.\n",
    "\n",
    "Overview:\n",
    "- Visualize MNIST in 2D using PCA.\n",
    "- Visualize MNIST in 2D using t-SNE."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "---\n",
    "# Setup\n",
    "Run these cells to get the tutorial started."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "# Imports\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "#@title Figure Settings\n",
    "import ipywidgets as widgets       # interactive display\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "\n",
    "nma_style = {\n",
    "    'figure.figsize' : (8, 6),\n",
    "    'figure.autolayout' : True,\n",
    "    'font.size' : 15,\n",
    "    'xtick.labelsize' : 'small',\n",
    "    'ytick.labelsize' : 'small',\n",
    "    'legend.fontsize' : 'small',\n",
    "    'axes.spines.top' : False,\n",
    "    'axes.spines.right' : False,\n",
    "    'xtick.major.size' : 5,\n",
    "    'ytick.major.size' : 5,\n",
    "}\n",
    "for key, value in nma_style.items():\n",
    "    plt.rcParams[key] = value\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "#@title Helper functions\n",
    "\n",
    "\n",
    "def visualize_components(component1, component2, labels, show=True):\n",
    "  \"\"\"\n",
    "  Plots a 2D representation of the data for visualization with categories\n",
    "  labelled as different colors.\n",
    "\n",
    "  Args:\n",
    "    component1 (numpy array of floats) : Vector of component 1 scores\n",
    "    component2 (numpy array of floats) : Vector of component 2 scores\n",
    "    labels (numpy array of floats)     : Vector corresponding to categories of\n",
    "                                         samples\n",
    "\n",
    "  Returns:\n",
    "    Nothing.\n",
    "\n",
    "  \"\"\"\n",
    "\n",
    "  plt.figure()\n",
    "  cmap = plt.cm.get_cmap('tab10')\n",
    "  plt.scatter(x=component1, y=component2, c=labels, cmap=cmap)\n",
    "  plt.xlabel('Component 1')\n",
    "  plt.ylabel('Component 2')\n",
    "  plt.colorbar(ticks=range(10))\n",
    "  plt.clim(-0.5, 9.5)\n",
    "  if show:\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "---\n",
    "# Section 1: Visualize MNIST in 2D using PCA\n",
    "\n",
    "In this exercise, we'll visualize the first few components of the MNIST dataset to look for evidence of structure in the data. But in this tutorial, we will also be interested in the label of each image (i.e., which numeral it is from 0 to 9). Start by running the following cell to reload the MNIST dataset (this takes a few seconds). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "from sklearn.datasets import fetch_openml\n",
    "mnist = fetch_openml(name='mnist_784', as_frame=False)\n",
    "X = mnist.data\n",
    "labels = [int(k) for k in mnist.target]\n",
    "labels = np.array(labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "To perform PCA, we now will use the method implemented in sklearn. Run the following cell to set the parameters of PCA - we will only look at the top 2 components because we will be visualizing the data in 2D."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "pca_model = PCA(n_components=2) # Initializes PCA\n",
    "pca_model.fit(X) # Performs PCA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "## Exercise 1: Visualization of MNIST in 2D using PCA\n",
    "\n",
    "Fill in the code below to perform PCA and visualize the top two  components. For better visualization, take only the first 2,000 samples of the data (this will also make t-SNE much faster in the following section of the tutorial so don't skip this step!)\n",
    "\n",
    "**Suggestions:**\n",
    "- Truncate the data matrix at 2,000 samples. You will also need to truncate the array of labels.\n",
    "- Perform PCA on the truncated data.\n",
    "- Use the function `visualize_components` to plot the labelled data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "help(visualize_components)\n",
    "help(pca_model.transform)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "#################################################\n",
    "## TODO for students: take only 2,000 samples and perform PCA\n",
    "#################################################\n",
    "\n",
    "# Take only the first 2000 samples with the corresponding labels\n",
    "# X, labels = ...\n",
    "# Perform PCA\n",
    "# scores = pca_model.transform(X)\n",
    "\n",
    "# Plot the data and reconstruction\n",
    "# visualize_components(...)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "# to_remove solution\n",
    "# Take only the first 2000 samples with the corresponding labels\n",
    "X, labels = X[:2000, :], labels[:2000]\n",
    "# Perform PCA\n",
    "scores = pca_model.transform(X)\n",
    "\n",
    "# Plot the data and reconstruction\n",
    "visualize_components(scores[:, 0], scores[:, 1], labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "## Think!\n",
    "- What do you see? Are different samples corresponding to the same numeral clustered together? Is there much overlap?\n",
    "- Do some pairs of numerals appear to be more distinguishable than others?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "---\n",
    "# Section 2: Visualize MNIST in 2D using t-SNE\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "Next we will analyze the same data using t-SNE, a nonlinear dimensionality reduction method that is useful for visualizing high dimensional data in 2D or 3D. Run the cell below to get started. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "from sklearn.manifold import TSNE\n",
    "tsne_model = TSNE(n_components=2, perplexity=30, random_state=2020)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "## Exercise 2: Apply t-SNE on MNIST\n",
    "First, we'll run t-SNE on the data to explore whether we can see more structure. The cell above defined the parameters that we will use to find our embedding (i.e, the low-dimensional representation of the data) and stored them in `model`. To run t-SNE on our data, use the function `model.fit_transform`.\n",
    "\n",
    "**Suggestions:**\n",
    "- Run t-SNE using the function `model.fit_transform`.\n",
    "- Plot the result data using `visualize_components`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "help(tsne_model.fit_transform)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "#################################################\n",
    "## TODO for students: perform tSNE and visualize the data\n",
    "#################################################\n",
    "\n",
    "# perform t-SNE\n",
    "embed = ...\n",
    "\n",
    "# Visualize the data\n",
    "# visualize_components(..., ..., labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "# to_remove solution\n",
    "# perform t-SNE\n",
    "embed = tsne_model.fit_transform(X)\n",
    "\n",
    "# Visualize the data\n",
    "visualize_components(embed[:, 0], embed[:, 1], labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "## Exercise 3: Run t-SNE with different perplexities\n",
    "\n",
    "Unlike PCA, t-SNE has a free parameter (the perplexity) that roughly determines how global vs. local information is weighted. Here we'll take a look at how the perplexity affects our interpretation of the results. \n",
    "\n",
    "**Steps:**\n",
    "- Rerun t-SNE (don't forget to re-initialize using the function `TSNE` as above) with a perplexity of 50, 5 and 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "def explore_perplexity(values):\n",
    "  \"\"\"\n",
    "  Plots a 2D representation of the data for visualization with categories\n",
    "  labelled as different colors using different perplexities.\n",
    "\n",
    "  Args:\n",
    "    values (list of floats) : list with perplexities to be visualized\n",
    "\n",
    "  Returns:\n",
    "    Nothing.\n",
    "\n",
    "  \"\"\"\n",
    "  for perp in values:\n",
    "\n",
    "    #################################################\n",
    "    ## TO DO for students: Insert your code here to redefine the t-SNE \"model\"\n",
    "    ## while setting the perplexity perform t-SNE on the data and plot the\n",
    "    ## results for perplexity = 50, 5, and 2 (set random_state to 2020\n",
    "    # Comment these lines when you complete the function\n",
    "    raise NotImplementedError(\"Student Exercise! Explore t-SNE with different perplexity\")\n",
    "    #################################################\n",
    "\n",
    "    # perform t-SNE\n",
    "    tsne_model = ...\n",
    "\n",
    "    embed = tsne_model.fit_transform(X)\n",
    "    visualize_components(embed[:, 0], embed[:, 1], labels, show=False)\n",
    "    plt.title(f\"perplexity: {perp}\")\n",
    "\n",
    "\n",
    "# Uncomment when you complete the function\n",
    "# values = [50, 5, 2]\n",
    "# explore_perplexity(values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab_type": "code",
    "execution": {}
   },
   "outputs": [],
   "source": [
    "# to_remove solution\n",
    "def explore_perplexity(values):\n",
    "  \"\"\"\n",
    "  Plots a 2D representation of the data for visualization with categories\n",
    "  labelled as different colors using different perplexities.\n",
    "\n",
    "  Args:\n",
    "    values (list of floats) : list with perplexities to be visualized\n",
    "\n",
    "  Returns:\n",
    "    Nothing.\n",
    "\n",
    "  \"\"\"\n",
    "\n",
    "  for perp in values:\n",
    "\n",
    "    # perform t-SNE\n",
    "    tsne_model = TSNE(n_components=2, perplexity=perp, random_state=2020)\n",
    "\n",
    "    embed = tsne_model.fit_transform(X)\n",
    "    visualize_components(embed[:, 0], embed[:, 1], labels, show=False)\n",
    "    plt.title(f\"perplexity: {perp}\")\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "# Uncomment when you complete the function\n",
    "values = [50, 5, 2]\n",
    "explore_perplexity(values)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "## Think!\n",
    "\n",
    "- What changes compared to your previous results using perplexity equal to 50? Do you see any clusters that have a different structure than before? \n",
    "- What changes in the embedding structure for perplexity equals to 5 or 2?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "---\n",
    "# Summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "execution": {}
   },
   "source": [
    "* We learned the difference between linear and nonlinear dimensionality reduction. While nonlinear methods can be more powerful, they can also be senseitive to noise. In contrast, linear methods are useful for their simplicity and robustness.\n",
    "* We compared PCA and t-SNE for data visualization. Using t-SNE, we could visualize clusters in the data corresponding to different digits. While PCA was able to separate some clusters (e.g., 0 vs 1), it performed poorly overall.\n",
    "* However, the results of t-SNE can change depending on the choice of perplexity. To learn more, we recommend this [Distill paper](https://distill.pub/2016/misread-tsne/).\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "include_colab_link": true,
   "name": "W3_TutorialBonus",
   "provenance": [],
   "toc_visible": true
  },
  "interpreter": {
   "hash": "63d742608f992112235285d8014d3ad9bd22d914fb5c109d9df6e126fac219ce"
  },
  "kernel": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "kernelspec": {
   "display_name": "Python 3.7.8 64-bit ('base': conda)",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
